
<?php
include "general_include.php";
include_once("adodb/dbconfig.php");


function getPostOrGetParam($param){
 	logToFile("getPostOrGetParam: "+$param);
	if(isset($_POST[$param]))
		return $_POST[$param];
	else{
		if(isset($_GET[$param]))
			return $_GET[$param];
		else
			return "";
	}
}

class Status{
	public static $AVAILABLE = 1;
	public static $ACTIVE = 2;
	public static $DELETED = 3;
	public static $PENDING = 4;
	public static $ACCEPTED = 5;
	public static $FINISHED = 6;
	public static $DECLINED = 7;
	public static $REQUESTED = 8;
}

class ErrorCode{
	public static $UNKNOWN= 0;
	public static $ALREADY_USED = -2;
	public static $NO_EVENTS = -3;
	public static $ALREADY_SCHEDULED = -4;
}

$SLOTS_ARRAY = array("h0","h1","h2","h3",
"h4","h5","h6","h7","h8","h9","h10","h11","h12","h13","h14","h15","h16","h17","h18","h19",
"h20","h21","h22","h23","h24","h25","h26","h27","h28","h29","h30","h31","h32","h33",
"h34","h35","h36","h37","h38","h39","h40","h41","h42","h43","h44","h45","h46","h47");

function logToFile($msg, $filename="test.log") {
	$fd = fopen($filename, "a");
	$str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $msg;
	fwrite($fd, $str . "\n");
	fclose($fd);
}


function login($username,$password){
	try{
		$db = new DBConnection();
		$db->getConnection();
		$sql = "select * from `nk_user` where `email`='".$username."' and `password`='".$password."'";
		$handle = mysql_query($sql);
		$linha = mysql_fetch_row($handle);
		
		$_SESSION['user_id'] = $linha[0];
		$_SESSION['logged_username'] = $linha[3];
		return true;
	}catch(Exception $e){
		return  $e->getMessage();
	}
}

class Event{
	public $status = "";
	public $calendarRef = "";
	public $description = "";
	public $requestoruserId = "";
	public $availableSpot = "";
	public $isEmpty = 0;
	public $requestorTxt = "";
	public $slot = "";
	public $calendarId = "";
	public $gameId = "";
	public $userId = "";
	public $day = "";
	public $month = "";
	public $year = "";
	
	function setStatus($status){
		$this->status = $status;
	}
	
	function setCalendarRef($calendarRef){
		$this->calendarRef = $calendarRef;
	}
	
	function setDescription($description){
		$this->description = $description;
	}
	
	function setRequestoruserId($requestoruserId){
		$this->requestoruserId = $requestoruserId;
	}
	
	function setAvailableSpot($availableSpot){
		$this->$availableSpot = $availableSpot;
	}
	
	function setIsEmpty($isEmpty){
		$this->isEmpty = $isEmpty;
	}
	
	function setRequestorTxt($requestorTxt){
		$this->requestorTxt = $requestorTxt;
	}
	function setGameId($gameId){
		$this->gameId = $gameId;
	}
	
	public function setEvent($status="",$description="",$availableSpot="",$gameId="", $requestoruserId="",$calendarRef="",$requestorTxt="",$isEmpty=0,$slot="") {		
		$this->status = $status;
		$this->description = $description;
		$this->availableSpot = $availableSpot;
		$this->requestoruserId = $requestoruserId;
		$this->calendarRef = $calendarRef;
		$this->requestorTxt = $requestorTxt;
		$this->isEmpty = $isEmpty;
		$this->slot = $slot;
		$this->gameId = $gameId;
	}
	
	public function __construct($event=null, $slot="", $row=null) {		
		if(is_null($event)){
			$this->isEmpty = true;
		}else{		
			list ($this->status, $this->description,$this->availableSpot, $this->gameId, $this->requestoruserId, $this->calendarRef, $this->requestorTxt) = split (',', $event);
		}
		$this->slot = $slot;
		
		if($row != null){
			$this->calendarId = $row->calendar_id;
			$this->userId = $row->user_id;
			$this->day = $row->day;
			$this->month = $row->month;
			$this->year = $row->year;
		}
	}
	
	public function __toString(){
		if($this->isEmpty){
			return "NULL";
		}
		return "'".$this->status.",".$this->description.",".$this->availableSpot.",".$this->gameId.",".$this->requestoruserId.",".$this->calendarRef.",".$this->requestorTxt."'";
	}
}

function getSlots($userid,$day,$slots){
	$ret = array();
	try{
		$db = new DBConnection();
		$db->getConnection();
	
		$sql = "select calendar_id, user_id, day, month, year, ";
		
		$i = 0;
		foreach ($slots as $slot){
			if($i == 0)
				$sql = $sql." `".$slot."` ";
			else
				$sql = $sql.", `".$slot."` ";
			$i++;
		}
		$sql = $sql."from `nk_user_calendar` where `user_id` = " .$userid;
		$sql = $sql." and `day` ='".$day."'";
		logToFile("SQL: ".$sql);
		$handle = mysql_query($sql);
		
		$row = mysql_fetch_object($handle);
		
		foreach ($slots as $slot){
			$ret[] = new Event($row->$slot, $slot, $row);

		}

	}catch(Exception $e){
		$ret['error'] = $e->getMessage();
	}
	return $ret;
}

function getSlotsByCalendarId($calendarId,$slots){
	$ret = array();
	try{
		$db = new DBConnection();
		$db->getConnection();

		$sql = "select calendar_id, user_id, day, month, year, ";

		$i = 0;
		foreach ($slots as $slot){
			if($i == 0)
				$sql = $sql." `".$slot."` ";
			else
				$sql = $sql.", `".$slot."` ";
			$i++;
		}
		$sql = $sql."from `nk_user_calendar` where `calendar_id` = ".$calendarId;
		logToFile("SQL: ".$sql);
		
// 		echo $sql;
		$handle = mysql_query($sql);

		$row = mysql_fetch_object($handle);

		foreach ($slots as $slot){
			$ret[] = new Event($row->$slot, $slot, $row);

		}

	}catch(Exception $e){
		$ret['error'] = $e->getMessage();
	}
	return $ret;
}



function listCalendar($userid,$day="0"){
	$ret = array();
	$ret['events'] = array();
	try{
		$db = new DBConnection();
		$db->getConnection();
	
		$sql = "select * from `nk_user_calendar` where `user_id` = " .$userid;
		if($day != "0"){
			$sql = $sql." and `day` ='".$day."'";
		}
		logToFile("SQL: ".$sql);
		$handle = mysql_query($sql);
		while ($row = mysql_fetch_object($handle)) {
			$ret['events'][] = array(
				$row->calendar_id,
				$row->user_id,
				$row->day,
				$row->month,
				$row->year,
				array(
					new Event($row->h0,"h0",$row),new Event($row->h1,"h1",$row),new Event($row->h2,"h2",$row),new Event($row->h3,"h3",$row),new Event($row->h4,"h4",$row),new Event($row->h5,"h5",$row),new Event($row->h6,"h6",$row),new Event($row->h7,"h7",$row),
					new Event($row->h8,"h8",$row),new Event($row->h9,"h9",$row),new Event($row->h10,"h10",$row),new Event($row->h11,"h11",$row),new Event($row->h12,"h12",$row),new Event($row->h13,"h13",$row),new Event($row->h14,"h14",$row),new Event($row->h15,"h15",$row),
					new Event($row->h16,"h16",$row),new Event($row->h17,"h17",$row),new Event($row->h18,"h18",$row),new Event($row->h19,"h19",$row),new Event($row->h20,"h20",$row),new Event($row->h21,"h21",$row),new Event($row->h22,"h22",$row),new Event($row->h23,"h23",$row),
					new Event($row->h24,"h24",$row),new Event($row->h25,"h25",$row),new Event($row->h26,"h26",$row),new Event($row->h27,"h27",$row),new Event($row->h28,"h28",$row),new Event($row->h29,"h29",$row),new Event($row->h30,"h30",$row),new Event($row->h31,"h31",$row),
					new Event($row->h32,"h32",$row),new Event($row->h33,"h33",$row),new Event($row->h34,"h34",$row),new Event($row->h35,"h35",$row),new Event($row->h36,"h36",$row),new Event($row->h37,"h37",$row),new Event($row->h38,"h38",$row),new Event($row->h39,"h39",$row),
					new Event($row->h40,"h40",$row),new Event($row->h41,"h41",$row),new Event($row->h42,"h42",$row),new Event($row->h43,"h43",$row),new Event($row->h44,"h44",$row),new Event($row->h45,"h45",$row),new Event($row->h46,"h46",$row),new Event($row->h47,"h47",$row)
				)
			);
			
		}
	}catch(Exception $e){
		$ret['error'] = $e->getMessage();
	}
	return $ret;
}

function updateSlots($slots, $requestoruserid, $calendarref, $description){
	$sl = array(); 
	
	foreach ($slots as $slot){
		$sl[] = $slot->slot;
	}
	return updateCalendar($slots[0]->calendarId, $slots[0]->userId, $slots[0]->day ,$sl, "1", $slots[0]->description, "0", $slots[0]->gameId, $requestoruserid, $calendarref, $description);
}

function updateCalendar($calendarId, $userid,$day,$slots,$status="1",$description="description",$availablespot="1", $gameId="0",$requestoruserid="0",$calendarref="0",$requestorTxt="",$remove=false){
	$ret = array();
	try{
		$db = new DBConnection();
		$db->getConnection();
		$event = new Event();
		$event->setEvent($status,$description,$availablespot,$gameId,$requestoruserid,$calendarref,$requestorTxt,$remove);
		$sql = "update `nk_user_calendar` set ";

		$i = 0;
		foreach ($slots as $slot){
			if($i == 0)
				$sql = $sql." `".$slot."` = ".$event;
			else
				$sql = $sql.", `".$slot."` = ".$event;
			$i++;
		}
	
		$sql = $sql." where `calendar_id` = ".$calendarId;
						
		if(mysql_query($sql)==false){
			logToFile('IsFail');
			$ret['IsSuccess'] = false;
			$ret['Msg'] = mysql_error();
		}else{
			logToFile('IsSuccess');
			$ret['IsSuccess'] = true;
			$ret['Msg'] = 'add success';
			$ret['Data'] = $day;
		}
	
	}catch(Exception $e){
		$ret['IsSuccess'] = false;
		$ret['Msg'] = $e->getMessage();
	}
	return $ret;
}

function insertCalendar($userid,$day,$slots,$status="1",$description="description",$availablespot="1", $gameId="0", $requestoruserid="0",$calendarref="0",$requestorTxt=""){
	$ret = array();
	try{
		$db = new DBConnection();
		$db->getConnection();
		
		list ($x, $month, $year) = split ('-', date('d-m-Y', $day));
		
		$event = new Event();
		$event->setEvent($status,$description,$availablespot,$gameId,$requestoruserid,$calendarref,$requestorTxt);		
		
		$sql = "insert into `nk_user_calendar` (`user_id`, `day`, `month`,`year`";
		
		foreach ($slots as $slot){
			$sql = $sql.",`".$slot."`";
		}
		$sql =  $sql.") values ('".$userid."', '".$day."', '".$month."', '".$year."'";
		
		foreach ($slots as $slot){
			$sql = $sql.", ".$event."";
		}
		$sql = $sql.")";		
		logToFile($sql."\n\n");
		if(mysql_query($sql)==false){
			$ret['IsSuccess'] = false;
			$ret['Msg'] = mysql_error();
		}else{
			$ret['IsSuccess'] = true;
			$ret['Msg'] = 'add success';
			$ret['Data'] = $day;
			$ret['Id'] = mysql_insert_id();
		}

	}catch(Exception $e){
		$ret['IsSuccess'] = false;
		$ret['Msg'] = $e->getMessage();
	}
	return $ret;
}


function getMonthCalendar($userid){
	$events = array();
	$fullCalendar = listCalendar($userid);
	if (empty($fullCalendar))
		return "{}";
	if(!array_key_exists("events", $fullCalendar))
		return "{}";
	
	$ret ="{";
	$i = 0;
	foreach ($fullCalendar['events'] as &$event) {
		list ($day, $month,$year) = split ('-', date('d-m-Y',$event[2]));
		$key = "D".$day."_".$month."_".$year;
		$sizeof_day = sizeof($event);
		$notEmptySpots = 0;
		$availableSpots = 0;
		foreach ($event[5] as &$hour){
			if($hour->isEmpty)
				continue;
			$notEmptySpots++;
			if($hour->availableSpot == 1){
				$availableSpots++;
				continue;
			}
		}
		if($i != 0)
			$ret = $ret.',';
		if($availableSpots == $notEmptySpots){
			$ret = $ret.'"'.$key.'":"ALL_FREE"';
		}else if($availableSpots == 0){
			$ret = $ret.'"'.$key.'":"ALL_BOOKED"';
		}else {
			$ret = $ret.'"'.$key.'":"AVAILABLE_SPOTS"';
		}
		$i++;
	}
	$ret = $ret."}";
	return $ret;
}

function changeStatus($id, $userid, $status){
	//TODO
}

function acceptSchedule($id, $userid){
	//TODO
}

function addSlots($day, $schedules, $userid, $description,$overwrite){
	$ret = array();
	$slots = getSlotsArray($schedules);
	$day = ($day/1000)+(24*3600);
	$event = listCalendar($userid,$day);
	$sizeof_day = sizeof($event);

	if(sizeof($event['events']) == 0){
		$ret = insertCalendar($userid, $day ,$slots, 1, $description);
	}else{
		if($overwrite == 0){
			$times = split(',', $schedules);
			foreach ($times as $time){
				if(!$event['events'][0][5][$time]->isEmpty){
					$ret['IsSuccess'] = false;
					$ret['ErrorCode'] = ErrorCode::$ALREADY_USED;
					return $ret;
				}
			}
		}
		$ret = updateCalendar($event['events'][0][0], $userid,$day,$slots,"1",$description);
	}
	return $ret;
}

function cancel($userid,$day,$schedules,$cancelClientEvents="0"){//TODO: 
	try{
		$ret = array();
		$slots = getSlotsArray($schedules);
		
		$clientEvents = array();
		$day = ($day/1000)+(24*3600);
		
		$event = getSlots($userid,$day,$slots);

		$sizeof_day = sizeof($event);
		if(sizeof($event) == 0){
			$ret['IsSuccess'] = false;
			$ret['ErrorCode'] = ErrorCode::$NO_EVENTS;
			return $ret;
		}
		else{
			$times = split(',', $schedules);
			if($cancelClientEvents == 0){
				foreach ($times as $time){
					if(!$event[$time]->isEmpty && $event[$time]->availableSpot != 1){
						$ret['IsSuccess'] = false;
						$ret['ErrorCode'] = ErrorCode::$ALREADY_SCHEDULED;
						return $ret;
					}
				}
			}else{
				$usersEvents = array();
				$calendarRefs = array();
				foreach ($event as $evn){
					if(!in_array($evn->calendarRef, $calendarRefs)){
						$events = getSlotsByCalendarId($evn->calendarRef,$slots);
						foreach ($events as $ev){
							$usersEvents[$ev->userId][]= $ev;
						}
						$calendarRefs[]=$evn->calendarRef;
					}
				}
				foreach ($usersEvents as $userEvents){
// 					print_r($userEvents);
					updateStatus($userEvents[0]->calendarId, $userEvents, Status::$DELETED);
				}
	
			}
	
			$ret = updateCalendar($event[0]->calendarId, $userid,$day,$slots,"1","","","","","","",true);
		}
	}catch(Exception $e){
		$ret['IsSuccess'] = false;
		$ret['Msg'] = $e->getMessage();
	}
	return $ret;
	
}

function updateStatus($calendarId, $slots, $status){	
	$sl = array();
	foreach ($slots as $slot){
		$sl[] = $slot->slot;
	}
	return updateCalendar($calendarId, $slots[0]->userId, $slots[0]->day ,$sl, $status, $slots[0]->description, "0", $slots[0]->gameId, $slots[0]->requestoruserid, $slots[0]->calendarref, $slots[0]->requestorTxt);

}

function getSlotsArray($schedules){
	$times = split(',', $schedules);
	global $SLOTS_ARRAY;
	
	foreach ($times as $time){
		$slots[] = $SLOTS_ARRAY[$time];
	}
	return $slots;
}

function scheduleLesson($userid, $day, $schedules, $description, $requestoruserid){
	
	$day = ($day/1000)+(24*3600);
	$ret = array();
	$slots = getSlotsArray($schedules);

	$calendarRef = "0";

	$event = listCalendar($requestoruserid,$day);
	$events = getSlots($userid,$day,$slots);
	if(sizeof($event['events']) > 0){
		$times = split(',', $schedules);
		foreach ($times as $time){
			if(!$event['events'][0][5][$time]->isEmpty){
				$ret['IsSuccess'] = false;
				$ret['ErrorCode'] = "-2";
				return $ret;
			}
		}
		
		$calendarRef = $event['events'][0][0];
		
		updateCalendar($event['events'][0][0], $requestoruserid,$day ,$slots,"2",$description,"0",$events[0]->gameId,"0",$events[0]->calendarId);

	}else{
		$ret = insertCalendar($requestoruserid, $day ,$slots, "2", $description,"0",$events[0]->gameId,"0", $events[0]->calendarId);
		$calendarRef = $ret['Id'];
	}
	updateSlots($events, $requestoruserid,$calendarRef,$description);
	
	return $ret;
}

function getUserInfo($userId){
	
	try{
		$db = new DBConnection();
		$db->getConnection();
		$sql = "select * from `nk_user` where `user_id` = '".$userId."'";
		$handle = mysql_query($sql);
		$row = mysql_fetch_object($handle);
		
		logToFile("SQL: ".$sql);
		
		if($userId == $_SESSION['user_id'])
			$row->owncalendar = '1';
		else
			$row->owncalendar = '0';
		return $row;
	}catch(Exception $e){
		return  $e->getMessage();
		logToFile("Exception: ".$e->getMessage());
	}	
}


function getUsers(){
	try{
		$db = new DBConnection();
		$db->getConnection();
	
		$sql = "select * from `nk_user`";
		$handle = mysql_query($sql);
		echo "<br/>";
		while ($row = mysql_fetch_object($handle)) {
			echo "<a onclick=\"showCalendar('".$row->user_id."');\" id=\"calendar_".$row->user_id."\" href=\"javascript:;\">".$row->user_id." - ".$row->email."</a>";
			echo "<br/>";
		}
	}catch(Exception $e){
		$ret['error'] = $e->getMessage();
	}
}

if(isset($_GET['method']) || isset($_POST['method'])){
	header('Content-type:text/javascript;charset=UTF-8');
	
	$method = getPostOrGetParam("method");
	
	switch ($method) {
		case "addslots":
			$ret = addSlots(getPostOrGetParam("day"), getPostOrGetParam("schedules"), $_SESSION['user_id'], getPostOrGetParam("description"),getPostOrGetParam("overwrite"));
			break;
			
		case "list":

			$userid = getPostOrGetParam("userid");
			if($userid == "")
				$userid = $_SESSION['user_id'];
			$day = getPostOrGetParam("day");
			$day = ($day/1000)+(24*3600);
			$ret = listCalendar($userid,$day);
			break;
		
		case "remove":
			$ret = removeCalendar( $_POST["calendarId"]);
			break;
		
		case "cancel":
			$ret = cancel(getPostOrGetParam("userid"), getPostOrGetParam("day"), getPostOrGetParam("schedules"), getPostOrGetParam("cancelClientEvents"));
			break;
			
		case "updateScheduleStatus":
			$ret = updateScheduleStatus( $_POST["calendarId"]);
			break;
			
		case "getmonthcalendar":
			$ret=getMonthCalendar(getPostOrGetParam("userid"));
			break;
			
		case "getUserInfo":
			$ret=getUserInfo(getPostOrGetParam("userid"));
			break;
			
		case "scheduleLesson":
			$ret = scheduleLesson(getPostOrGetParam("userid"), getPostOrGetParam("day"), getPostOrGetParam("schedules"), getPostOrGetParam("description"), $_SESSION['user_id']	);
			break;
				
	}
	echo json_encode($ret); 

}

?>